﻿using BusinessLogic;
using PCTInterface.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Utility;

namespace PCTInterface
{
    public class OperationWeb
    {
        public Dictionary<string, Func<string>> InitMethods(Dictionary<string, object> paramsValues)
        {
            Dictionary<string, Func<string>> dicFunc = new Dictionary<string, Func<string>>();
            string jsonType = string.Empty;
            if (paramsValues.ContainsKey("JSON_TYPE"))
            {
                jsonType = paramsValues["JSON_TYPE"].ToString();
            }
            dicFunc["list"] = new Func<string>(() =>
            {
                return DoList(paramsValues);
            });

            dicFunc["merge_list"] = new Func<string>(() =>
            {
                return DoMergeList(paramsValues);
            });

            dicFunc["query_text_list"] = new Func<string>(() =>
            {
                return DoQueryTextList(paramsValues);
            });

            dicFunc["query_text_merge_list"] = new Func<string>(() =>
            {
                return DoQueryTextMergeList(paramsValues);
            });

            dicFunc["select"] = new Func<string>(() =>
            {
                return DoSelect(paramsValues);
            });

            dicFunc["select_row"] = new Func<string>(() =>
            {
                return DoSelectRow(paramsValues);
            });

            dicFunc["menu"] = new Func<string>(() =>
            {
                return DoMenu(paramsValues);
            });

            dicFunc["login"] = new Func<string>(() =>
            {
                return DoLogin(paramsValues);
            });

            dicFunc["batch_update_transation"] = new Func<string>(() =>
            {
                return DoBatchUpdateTransation(paramsValues);
            });

            dicFunc["report_build"] = new Func<string>(() =>
            {
                return new OperationWeb().ReportBuild(paramsValues);
            });
            dicFunc["structs"] = new Func<string>(() =>
            {
                return DoStruct(paramsValues);
            });
            dicFunc["default"] = new Func<string>(() =>
            {
                return DoDefault(paramsValues);
            });

            dicFunc["static"] = new Func<string>(() =>
            {
                return DoQueryStatic(paramsValues);
            });
            return dicFunc;
        }

        /// <summary>
        /// 验证提交Ajax操作是否合法
        /// </summary>
        /// <param name="formParams"></param>
        /// <returns></returns
        public string ValidateAction(IDictionary<string, object> formParams)
        {
            if (!formParams.Keys.Contains(Constant.OP_NAME))
            {
                throw new NullReferenceException("方法参数未设置");
                // Response.Write(JSONHelper.formatReplyJson(false,""));
                // return;
            }

            if (!formParams.ContainsKey(Constant.SP_NAME) && !formParams.ContainsKey(Constant.CACHE_CODE))
            {
                throw new NullReferenceException("命令参数未设置");
            }

            string m = formParams[Constant.OP_NAME].ToString().ToLower();
            if (!new List<string>(new string[] { "login" }).Contains(m))
            {
                if ((!formParams.ContainsKey("EHUSER") || string.IsNullOrEmpty(formParams["EHUSER"].ToString())) && !formParams.ContainsKey("NO_LOGIN"))
                {
                    throw new NullReferenceException("用户未登陆或会话已过期,请重新登陆系统");
                }
            }
            return m;
        }

        public string DoQueryNode(IDictionary<string, object> formParams) {
            string detail_string = formParams["DETAIL_STRING"].ToString();
            JsonLogic bll = JsonLogic.Instance;
            return "";
        }

        public string DoQueryStatic(IDictionary<string, object> formParams)
        {
            string fullPath = HttpContext.Current.Server.MapPath("~");

            string fileName = (string)formParams["SP_NAME"];
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new NullReferenceException("命令参数未设置");
            }
            if (fileName.IndexOf(@"\\") > -1 || fileName.IndexOf("/") > -1)
            {
                fullPath = Path.Combine(fullPath, fileName);
            }
            else
            {
                fullPath = Path.Combine(fullPath, "static", fileName);
            }
            string content = "";
            if (File.Exists(fullPath))
            {
                content = File.ReadAllText(fullPath, Encoding.UTF8);
            }
            else
            {
                throw new IOException("静态文件不存在");
            }
            if (content.Trim().StartsWith("[") && formParams.ContainsKey("QUERY"))
            {
                DataTable dtbl = JSONHelper.Instance.JavaScriptDeserializationMachion<DataTable>(content);
                dtbl.DefaultView.RowFilter = formParams["QUERY"].ToString();
                DataTable newDtbl = dtbl.DefaultView.ToTable();
                content = JSONHelper.Instance.JavaScriptConvertMachion(newDtbl);
            }
            if (formParams.ContainsKey("JSON_TYPE") && formParams["JSON_TYPE"].ToString().ToUpper() == "TOTAL")
            {
                if (content.Trim().StartsWith("["))
                {
                    content = "{" + "\"total\":50,\"rows\":" + content + "}";
                }
            }
            return content;

        }

        string DoList(Dictionary<string, object> pass_params)
        {
            string result = "";
            Dictionary<string, object> paramsValues = new Dictionary<string, object>();
            DataTable dtbl= GetCacheDataTable(pass_params, out paramsValues);
            JsonLogic bll = JsonLogic.Instance;
            if (dtbl == null) {         
                dtbl= bll.GetTable(paramsValues, true,false);
                SetCacheDataTable(pass_params, dtbl);
            }
            //dtbl = bll.GetLocalQueryTable(dtbl, paramsValues);
            string jsonType = GetJsonType(paramsValues);
            if (jsonType == "nototal")
            {
                dtbl = bll.PagationCloneDataTable(dtbl, paramsValues, true);
                result = bll.jsonSelect(dtbl, paramsValues);
            }
            else
            {          
                paramsValues["_totalRows"] = bll.SelectedEffectRows;
                dtbl = bll.PagationCloneDataTable(dtbl, paramsValues, true);
                result = bll.GetPagationJson(dtbl, paramsValues);
            }
            return result;
        }

        string DoStruct(Dictionary<string, object> pass_params)
        {
            JsonLogic bll = JsonLogic.Instance;
            //Dictionary<string, object> paramsValues = new Dictionary<string, object>();
            DataTable dtbl = bll.GetTable(pass_params,false,false);
            if (dtbl == null)
            {
                return "{}";
            }
            List<object> lstColumns = new List<object>();
            List<object> lstRow = new List<object>();
            DataRow drow = null;
            Dictionary<string, string> dicFields = null;
            if (dtbl.Rows.Count > 0)
            {
                drow = dtbl.Rows[0];
                dicFields = new Dictionary<string, string>();
            }

            foreach (DataColumn col in dtbl.Columns)
            {
                lstColumns.Add(new { COLUMN = col.ColumnName, DATA_TYPE = col.DataType.Name });
                if (dicFields != null) { 
                    dicFields[col.ColumnName] = drow[col].ToString();
                }
            }
            if(dicFields!=null)
            {
               lstRow.Add(dicFields);
             }
           
            return "{" + string.Format("\"structs\":{0},\"rows\":{1}", JSONHelper.Instance.JavaScriptConvertMachion(lstColumns), JSONHelper.Instance.JavaScriptConvertMachion(lstRow)) + "}";
        }

        string DoMergeList(Dictionary<string, object> paramsValues)
        {
            JsonLogic bll = JsonLogic.Instance;
            DataTable dtbl = bll.GetMergeTable(paramsValues);
            int totalRows = bll.SelectedEffectRows;
            string result = "";
            string jsonType = GetJsonType(paramsValues);
            if (jsonType == "nototal")
            {
                result = bll.jsonSelect(dtbl, paramsValues);
            }
            else
            {      
                paramsValues["_totalRows"] = totalRows;
                result = bll.GetPagationJson(dtbl, paramsValues);
            }
            return result;
        }

        string DoQueryTextList(Dictionary<string, object> pass_params)
        {
            JsonLogic bll = JsonLogic.Instance;
            string result = "";     
            Dictionary<string, object> paramsValues = new Dictionary<string, object>();
            DataTable dtblData = GetCacheDataTable(pass_params, out paramsValues);
            if (dtblData == null)
            {
                dtblData = bll.QueryTableAsText(paramsValues);
                SetCacheDataTable(pass_params, dtblData);
            }
            string jsonType = GetJsonType(paramsValues);
            if (jsonType == "nototal")
            {
                dtblData = bll.PagationCloneDataTable(dtblData, paramsValues, true);
                result = bll.jsonSelect(dtblData, paramsValues);
            }
            else
            {
                dtblData = bll.PagationCloneDataTable(dtblData, paramsValues, true);
                int totalRows = dtblData.Rows.Count;
                paramsValues["_totalRows"] = totalRows;
                result = bll.GetPagationJson(dtblData, paramsValues);
            }
            return result;
        }

        string DoQueryTextMergeList(Dictionary<string, object> paramsValues)
        {
            JsonLogic bll = JsonLogic.Instance;
            string result = "";
            string jsonType = GetJsonType(paramsValues);
            if (jsonType == "nototal")
            {
                result = bll.jsonSelect(bll.QueryMergeTableAsText(paramsValues), paramsValues);
            }
            else
            {
                DataTable dtblData = bll.QueryMergeTableAsText(paramsValues);
                int totalRows = bll.SelectedEffectRows;
                paramsValues["_totalRows"] = totalRows;
                result = bll.GetPagationJson(dtblData, paramsValues);
            }
            return result;
        }

        string DoMenu(Dictionary<string, object> paramsValues)
        {
            JsonLogic bll = JsonLogic.Instance;
            string result = "";
            bll.jsonMenu(bll.GetTable(paramsValues, false), "MENU_KEY", "PARENT_MENU_KEY", "SUB_MENU");
            return result;
        }

        string DoSelect(Dictionary<string, object> pass_params)
        {
            JsonLogic bll = JsonLogic.Instance;
            Dictionary<string, object> paramsValues = new Dictionary<string, object>();
            DataTable dtbl = GetCacheDataTable(pass_params, out paramsValues);
            if (dtbl == null)
            {
                dtbl = bll.GetTable(paramsValues, true);
                SetCacheDataTable(pass_params, dtbl);
            }
            dtbl = bll.PagationCloneDataTable(dtbl, paramsValues, true);
            return bll.jsonSelect(dtbl, paramsValues);
        }

        string DoSelectRow(Dictionary<string, object> pass_params)
        {
            JsonLogic bll = JsonLogic.Instance;
            Dictionary<string, object> paramsValues = new Dictionary<string, object>();
            DataTable dtbl = GetCacheDataTable(pass_params, out paramsValues);
            if (dtbl == null)
            {
                dtbl = bll.SelectRow(paramsValues, true);
                SetCacheDataTable(pass_params, dtbl);
            }
            return bll.jsonSelect(dtbl, paramsValues);
        }

        string DoLogin(Dictionary<string, object> formParams)
        {
            JsonLogic bll = JsonLogic.Instance;
            HttpContext context = HttpContext.Current;
            try
            {
                DataSet outputDataSet = null;
                IDictionary<string, object> outputParams = bll.Dulpex(formParams, out outputDataSet);
                if (outputParams["RETURN_CODE"].ToString().Equals("0"))
                {
                    context.Session[Constant.CONST_SESSION_USER_NAME] = outputParams[Constant.CONST_SESSION_USER_NAME];
                    context.Session[Constant.CONST_SESSION_USER] = outputParams[Constant.CONST_SESSION_USER];
                    context.Session[Constant.CONST_LANG] = outputParams["IVBABY_LANGUAGE"];
                    formParams[Constant.SP_NAME] = "SP_USER_RELATION_LIST";
                    formParams[Constant.CONST_SESSION_USER] = outputParams[Constant.CONST_SESSION_USER];
                    DataTable dt = bll.GetTable(formParams, false);
                    formParams[Constant.CONST_SESSION_DATA] = dt;

                    formParams["IP"] = HttpContext.Current.Request.UserHostAddress;
                    formParams["LOGIN_TYPE_VARIABLE_KEY"] = "20206";
                    formParams["LAST_LOGIN_DATE"] = DateTime.Now.ToLongDateString();
                    formParams["EHUSER"] = context.Session[Constant.CONST_SESSION_USER];
                    formParams["COMMENT"] = "";
                    formParams[Constant.SP_NAME] = "SP_USER_HISTORY_INSERT";
                    outputParams = bll.Excute(formParams);
                }
                return bll.jsonOutput(outputParams);
            }
            catch
            {
                Dictionary<string, object> errReturn = new Dictionary<string, object>();
                errReturn["RETURN_CODE"] = 9;
                errReturn["RETURN_MESSAGE"] = "登陆失败";
                return JsonLogic.Instance.jsonOutput(errReturn);
            }
        }

        public string DoBatchUpdateTransation(IDictionary<string, object> formParams)
        {
            JsonLogic bll = JsonLogic.Instance;
           
            List<IDictionary<string, object>> details = JSONHelper.Instance.JavaScriptDeserializationMachion<List<IDictionary<string, object>>>(formParams["DETAIL_STRING"].ToString());
            List<IDictionary<string, object>> standardParams = new List<IDictionary<string, object>>();

            foreach (Dictionary<string, object> detail in details)
            {
                detail["EHUSER"] = formParams["EHUSER"];
                detail["DB_NAME"] = formParams["DB_NAME"];
                standardParams.Add(detail);
            }
            return bll.jsonOutput(bll.ExcuteTransation(standardParams));
        }

        string DoDefault(Dictionary<string, object> formParams)
        {
            JsonLogic bll = JsonLogic.Instance;
            return bll.jsonOutput(bll.Excute(formParams));
        }

        string GetJsonType(Dictionary<string, object> paramsValues)
        {
            return paramsValues.ContainsKey("JSON_TYPE") ? paramsValues["JSON_TYPE"].ToString().ToLower() : "";
        }

        public string ReportBuild(IDictionary<string, object> formParams)
        {
            string fullFilePath;
            HttpContext context = HttpContext.Current;

            DataSet dsetReport = JsonLogic.Instance.GetDataSet(formParams);
            if (dsetReport == null)
            {
                throw new Exception("报表执行报错");
            }
                
            string currentDir = context.Server.MapPath("~");
            string fullDir = Path.Combine(currentDir, "report_bin");

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["REPORT_BIN"]))
            {
                fullDir = ConfigurationManager.AppSettings["REPORT_BIN"];
            }
            if (!Directory.Exists(fullDir))
            {
                Directory.CreateDirectory(fullDir);
            }
            fullFilePath = Path.Combine(fullDir, formParams["REPORT_NAME"] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss_fff") + ".xls");
            Utility.ExcelForReport.Instance.ExportExcel(dsetReport, fullFilePath, false);
            return fullFilePath;
                //return "[{" + string.Format("\"success\":1,\"fileurl\":\"{0}\"", fullFilePath.Replace("\\", "/")) + "}]";

        }

        public DataTable GetCacheDataTable(Dictionary<string, object> formParams,out Dictionary<string, object> pass_params)
        {
            pass_params = new Dictionary<string, object>();
            foreach (string key in formParams.Keys)
            {
                if (key != Constant.CACHE_CODE)
                {
                    pass_params[key] = formParams[key];
                }
            }
            try
            {
                if (formParams.ContainsKey(Constant.CACHE_CODE))
                {
                    Dictionary<string, object> cache_dic = JSONHelper.Instance.JavaScriptDeserializationMachion<Dictionary<string, object>>(formParams[Constant.CACHE_CODE].ToString());
                    foreach (string cache_key in cache_dic.Keys)
                    {
                        pass_params[cache_key] = cache_dic[cache_key];
                    }
                    if (cache_dic.Keys.Count > 0)
                    {
                        object data = CacheQueryData.GetCache(formParams);
                        if (data != null && data is DataTable)
                        {
                            return (DataTable)data;
                        }
                    }
                }

            }
            catch{}
            return null;
        }

        public void SetCacheDataTable(Dictionary<string, object> pass_params,object data)
        {
            CacheQueryData.SetCache(pass_params, data);
        }



    }
}